package org.ssp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.KeyPair;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.ssp.base.GetRandomInt;
import org.ssp.dao.UserDao;
import org.ssp.impl.UserImpl;
import org.ssp.pojo.Token;
import org.ssp.pojo.User;
import org.ssp.util.BindCodeUtil;
import org.ssp.util.CommonUtil;
import org.ssp.util.JCryptionUtil;
import org.ssp.util.SmsUtil;

/**
 * 注册
 */
@WebServlet("/sigin")
public class SiginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	   String method=request.getParameter("method");
	   if("page".equals(method)){//请求sigin页面
	     try { 
		   //创建keypair
			JCryptionUtil jcryption=new JCryptionUtil();
			KeyPair keys=null;
			keys=jcryption.generateKeypair(512);
			//保存秘钥到session
			request.getSession().setAttribute("keys", keys);
			String e=JCryptionUtil.getPublicKeyModulus(keys);
			String n=JCryptionUtil.getPublicKeyExponent(keys);
			String md=String.valueOf(JCryptionUtil.getMaxDigits(512));
			//同时将公钥返回给前台用于密码加密传输
		    request.setAttribute("publickey", e);
		    request.setAttribute("exponent", n);
		    request.setAttribute("maxdigit", md);
			} catch (Exception e) {
				e.printStackTrace();
		 }
		 request.getRequestDispatcher("/WEB-INF/page/user/sigin.jsp").forward(request, response);
	   }else if("checkphone".equals(method)){//验证手机是否注册过
		   String phone=request.getParameter("mobile");
		   UserDao userd=new UserImpl();
		   if(userd.findByPhone(phone)!=null){//
			    JSONObject json = new JSONObject();
				json.put("msg", "该手机号已注册过");
				response.setContentType("application/x-json;charset=utf-8");
				PrintWriter out=response.getWriter();
				out.write(json.toString());
		   }
		   return;
		   
	   }else if("sendcode".equals(method)){//发送手机验证码
		   String phone=request.getParameter("mobile");
		   System.out.println(phone);

		  //生成随机4位验证码，保存session
		   String code4= GetRandomInt.getRandomString(4);
		   request.getSession().setAttribute("code4", code4);
		   //发送短信验证码
		   String testUsername = "Goodsu"; //在短信宝注册的用户名
	       String testPassword = "ssp08294112"; //在短信宝注册的密码
	       String testPhone = phone;
	         // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
	       String testContent = "【廣州歐星留學】您的验证码是"+code4;
	       String httpUrl = "http://api.smsbao.com/sms";
	       SmsUtil.sendMessage(httpUrl, testUsername,testPassword,testPhone,testContent);
	       return;
		   
	  }else if("checkcode".equals(method)){//微信账户绑定验证码
		  String code=request.getParameter("code");
		  if(!code.equals(request.getSession().getAttribute("code4"))){
			    JSONObject json = new JSONObject();
				json.put("msg", "验证码错误，重新输入");
				response.setContentType("application/x-json;charset=utf-8");
				PrintWriter out=response.getWriter();
				out.write(json.toString());
		  }
		  return;
	  }else if("sigin".equals(method)){//注册完成并跳转
		   String phone=request.getParameter("phone");
		   String pwd=request.getParameter("pwd");//加过密的密码
		   String code=request.getParameter("checkcode");
		   //判断手机验证码是否正确
		   //rsa解密
		   KeyPair keys = (KeyPair) request.getSession().getAttribute("keys");
		   String decryptedPwd=null;
			try {
				decryptedPwd = JCryptionUtil.decrypt(pwd, keys);
				System.out.println(decryptedPwd);

			} catch (Exception e) {
				e.printStackTrace();
			}
			//创建user对象，保存到数据库，完成注册
			User user=new User();
			user.setPhone(phone);
			user.setPassword(decryptedPwd);
			UserDao userdao=new UserImpl();
			userdao.addUser(user);
			request.getRequestDispatcher("/WEB-INF/page/user/usercenter.jsp").forward(request, response);
	  }else if("bindcode".equals(method)){//生成并返回二维码
		    String json="{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
			System.out.println(json);
			//获取access_token
			Token token = null;
			try {
				token = CommonUtil.getAccessToken("wxf34da76143f5050d", "7a6df503a9afaa70601d652cfb99b16d");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(token.getAccessToken());
			String str=BindCodeUtil.requestTicket(json, token.getAccessToken());
			String code=BindCodeUtil.BINDCODE_URL.replace("TICKET", str);
		    JSONObject jsono=new JSONObject();
		    jsono.put("code", code);
		    response.setContentType("application/x-json;charset=utf-8");
		    PrintWriter out=response.getWriter();
		    out.write(jsono.toString());
		    return;
	  }
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
